import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 商品 id
    goods_id: '',
    // 商品的详情
    goodsInfo: {},
    // 收货地址
    addressInfo: null
  }

  // 获取商品详情数据
  async getGoodDetail() {
    const { data: res } = await wepy.get('/goods/detail', {
      goods_id: this.goods_id
    })
    
    // 判断返回的数据是否成功
    if (res.meta.status !== 200) {
      return wepy.baseToast()
    }

    this.goodsInfo = res.message
    this.$apply()
  }

  computed = {
    addressStr () {
      if (this.addressInfo === null) {
        return '请选择收货地址'
      }

      const {provinceName, cityName, countyName, detailInfo} = this.addressInfo
      return provinceName + cityName + countyName + detailInfo
    },

    total () {
      return this.$parent.globalData.total
    }
  }

  methods = {
    previewImage (current) {
      wepy.previewImage({
        // 使用 map 方法返回图片列表
        urls: this.goodsInfo.pics.map(item => item.pics_big),
        // 当前显示的图片地址
        current: current
      })
    },

    async chooseAddress () {
      const res = await wepy.chooseAddress().catch(err => err)

      if (res.errMsg !== 'chooseAddress:ok') {
        return wepy.baseToast('收货地址选择失败')
      }

      this.addressInfo = res
      wepy.setStorageSync('address', res)
    },

    // 加入购物车
    addToCart () {
      // console.log(this.$parent.globalData)
      // this.$parent.test()
      this.$parent.addGoodsToCart(this.goodsInfo)
      // 获取商品的信息
      // console.log(this.goodsInfo)
      // 给用户一个提示
      wepy.showToast({
        title: '加入购物车成功',
        icon: 'success'
      })
    }
  }

  onLoad(options) {
    this.goods_id = options.goods_id
    this.getGoodDetail()
  }
}
